package com.zjlanyun.erp.interior.warehouse;

import android.app.ActivityManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.AndroidVersions;
import com.alibaba.fastjson.JSON;
import com.fntech.m10.gpio.M10_GPIO;
import com.fntech.m10a.gpio.M10A_GPIO;
import com.yolanda.nohttp.rest.Response;
import com.zjlanyun.erp.Data;
import com.zjlanyun.erp.R;
import com.zjlanyun.erp.config.AppConfig;
import com.zjlanyun.erp.interior.CommonList;
import com.zjlanyun.erp.interior.production.Loading;
import com.zjlanyun.erp.network.WebApi;
import com.zjlanyun.erp.nohttp.HttpRequest;
import com.zjlanyun.erp.nohttp.SimpleHttpListener;
import com.zjlanyun.erp.rfid.m10.u8.activity.OutPowerActivity;
import com.zjlanyun.erp.rfid.m10.u8.service.IOManager;
import com.zjlanyun.erp.rfid.m10.u8.service.SoundManager;
import com.zjlanyun.erp.utils.Toastor;
import com.zjlanyun.erp.view.BaseRFIDActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.OnClick;

public class BeginData extends BaseRFIDActivity {

    @Bind(R.id.ll_submit) LinearLayout ll_submit;
    @Bind(R.id.tv_FGongxuName) TextView tv_FGongxuName;
    @Bind(R.id.et_FNumber) EditText et_FNumber;
    @Bind(R.id.tv_FName) TextView tv_FName;
    @Bind(R.id.tv_FModel) TextView tv_FModel;
    @Bind(R.id.tv_FUnit) TextView tv_FUnit;
    @Bind(R.id.tv_epc) TextView tv_epc;
    @Bind(R.id.et_FCLQty) EditText et_FCLQty;
    @Bind(R.id.et_FQty) EditText et_FQty;

    @Bind(R.id.tv_result) TextView tv_result;
    @Bind(R.id.tv_status) TextView tv_status;

    private boolean scaning = false;
    private String apiUrl = "";
    private String epc = "";
    private String barcode = "";
    public static SoundManager mSoundManager = new SoundManager();
    private ArrayList<HashMap<String, Object>> mGongxuList;
    private String FGongxuNO = "";

    public static final int REQUESTCODE_SELECTGONGXU = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.begin_data);
        initBaseView();
        initView();
        initScan();
        getGongxu();
    }

    private void initView() {
        title.setText("期初盘点");
        ll_submit.setVisibility(View.VISIBLE);
        apiUrl = WebApi.warehouse();
    }

    private void initScan() {
        mSoundManager.initSounds(this);
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOn();
            IOManager.INSTANCE.InitComm(handler);
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOn();
            IOManager.INSTANCE.InitCommA(handler);
        }
    }

    @Override
    protected void onResume() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOn();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOn();
        }
        super.onResume();
    }

    /**
     * 获取工序
     */
    private void getGongxu() {
        mGongxuList = new ArrayList<>();
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getGongxu", true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                JSONArray gongxu = data.optJSONArray("gongxu");
                for (int i = 0; i < gongxu.length(); i++) {
                    JSONObject item = gongxu.optJSONObject(i);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("FName", item.optString("FName"));
                    map.put("FNumber", item.optString("FNumber"));
                    mGongxuList.add(map);
                }
            }
        });
    }

    /**
     * 选择工序
     */
    @OnClick(R.id.btn_select_gongxu)
    public void select_gongxu() {
        if (mGongxuList.size() > 0) {
            Bundle bundle = new Bundle();
            bundle.putString("title", "选择工序");
            bundle.putIntArray("layout", new int[]{R.id.tv1});
            bundle.putStringArray("field", new String[]{"FName"});
            bundle.putString("list", JSON.toJSONString(mGongxuList));
            bundle.putString("action", "common");
            Intent intent = new Intent(mContext, CommonList.class);
            intent.putExtras(bundle);
            startActivityForResult(intent, REQUESTCODE_SELECTGONGXU);
        } else {
            Toastor.getInstance().showShortToast("无工序数据，请返回重新打开页面");
        }
    }

    @OnClick(R.id.btn_query)
    public void query() {
        if (et_FNumber.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入物料代码或扫描条码");
            return;
        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("FNumber", et_FNumber.getText().toString());
        HttpRequest client = new HttpRequest(mContext, apiUrl, "getMateriel", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                JSONObject data = response.get().optJSONObject("data");
                tv_FName.setText(data.optString("FName"));
                tv_FModel.setText(data.optString("FModel"));
                tv_FUnit.setText(data.optString("FUnit"));
            }

            @Override
            public void onError(int what, Response<JSONObject> response) {
                tv_FName.setText("");
                tv_FModel.setText("");
            }
        });
    }

    /**
     * 开始扫描
     */
    public void startScan() {
        tv_epc.setText("");
        tv_status.setText("盘询开始");
        scanNumber = 1;
        scaning = true;
        super.startScan();
    }

    /**
     * 停止扫描
     */
    public void stopScan() {
        tv_status.setText("盘询结束");
        scaning = false;
        super.stopScan();
    }

    public void refreshText() {
        super.refreshText();
        tv_result.setText(String.format("扫描到:%d个", m_curInventoryBuffer.lsTagList.size()));
        if (m_curInventoryBuffer.lsTagList.size() > 0) {
            tv_epc.setText(m_curInventoryBuffer.lsTagList.get(0).getStrEPC().replace(" ", ""));
        }
    }

    @OnClick(R.id.ll_submit)
    public void postBeginData() {
        if (tv_epc.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请扫卡");
            return;
        } else if (et_FNumber.getText().toString().equals("")) {
            Toastor.getInstance().showShortToast("请输入物料代码或扫描条码");
            return;
        } else if (FGongxuNO.equals("")) {
            Toastor.getInstance().showShortToast("请选择工序");
            return;
        }

        HashMap<String, Object> param = new HashMap<>();
        param.put("FBillNO", tv_epc.getText().toString());
        param.put("FGongxuNO", FGongxuNO);
        param.put("FNumber", et_FNumber.getText().toString());
        param.put("FCLQty", et_FCLQty.getText().toString());
        param.put("FQty", et_FQty.getText().toString());
        HttpRequest client = new HttpRequest(mContext, apiUrl, "postBeginData", JSON.toJSONString(param), true, true);
        client.send(new SimpleHttpListener<JSONObject>() {
            @Override
            public void onSucceed(int what, Response<JSONObject> response) {
                Toastor.getInstance().showShortToast(R.string.submit_success);
                cleanEPC();
                cleanBarcode();
            }
        });
    }

    private void cleanBarcode() {
        barcode = "";
        et_FNumber.setText("");
        tv_FName.setText("");
        tv_FModel.setText("");
        et_FCLQty.setText("");
        et_FQty.setText("");
    }

    private void cleanEPC() {
        epc = "";
        tv_epc.setText("");
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    byte[] ret = (byte[]) msg.obj;
                    try {
                        barcode = new String(ret, "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    System.out.println(barcode);
                    et_FNumber.setText(barcode);
                    et_FNumber.setFocusableInTouchMode(true);
                    et_FNumber.setFocusable(true);
                    query();
                    mSoundManager.playSound();
                    break;
                default:
                    break;
            }
        }
    };

    private static void writeFile(String fileName, String writestr) {
        try {
            FileOutputStream fout = new FileOutputStream(fileName);
            byte[] bytes = writestr.getBytes();
            fout.write(bytes);
            fout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        System.out.println(keyCode);
        if (keyCode == 80 && Build.MODEL.equals(Data.RFID_DEVICE)) {
            if (scaning) {
                stopScan();
            } else {
                startScan();
            }
            return false;
        } else if ((keyCode == 21 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 22 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            et_FNumber.setFocusableInTouchMode(false);
            et_FNumber.setFocusable(false);
            writeFile("/sys/class/gpio/gpio907/direction", "out");
            writeFile("/sys/class/gpio/gpio907/value", "0");
            writeFile("/sys/class/gpio/gpio909/value", "1");
            return false;
        } else if ((keyCode == 131 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 132 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 133 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            Intent intent = new Intent(mContext, OutPowerActivity.class);
            intent.putExtra("from", "RFID" + className);
            startActivity(intent);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if ((keyCode == 21 && Build.MODEL.equals(Data.RFID_DEVICE)) || (keyCode == 22 && Build.MODEL.equals(Data.RFID_DEVICE))) {
            writeFile("/sys/class/gpio/gpio907/value", "1");
            writeFile("/sys/class/gpio/gpio909/value", "1");
            return false;
        }
        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_4_0_3)) {
            M10_GPIO._1D_PowerOff();
            IOManager.INSTANCE.DeInitComm();
        } else if (android.os.Build.VERSION.RELEASE.equals(AndroidVersions.V_5_1_1)) {
            M10A_GPIO.BdPowerOff();
            IOManager.INSTANCE.DeInitCommA();
        }
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUESTCODE_SELECTGONGXU && resultCode == RESULT_OK && data != null) {
            Bundle bundle = data.getExtras();
            int p = bundle.getInt("position");
            tv_FGongxuName.setText(mGongxuList.get(p).get("FName").toString());
            FGongxuNO = mGongxuList.get(p).get("FNumber").toString();
        }
    }
}
